import { computed, defineComponent, inject, onBeforeMount, reactive, ref, SetupContext, watch } from 'vue';
import { memoryVoicePlayBarProps, MemoryVoicePalyBarProps } from './play-bar.props';
import './play-bar.scss';
import { PlayModes, PlayState, ProficiencyLevel, ResourceCourse, ResourceInfo, ShareType, UtteranceSettings } from '../../composition/types';
import { useTextToSpeech } from '../../composition/use-textToSpeech';
import { highlight } from '../../composition/hight-light';

export default defineComponent({
    name: 'FMemoryVoicePlayBar',
    props: memoryVoicePlayBarProps,
    emits: [],
    setup(props: MemoryVoicePalyBarProps, context: SetupContext) {
        const curInfo = ref(props.curResource);
        // 记录当前科目
        const curCourse = ref<Array<ResourceInfo>>([]);
        // API配置
        var curUtteranceSettings = ref({ lang: 'zh-CN', volume: 1, rate: 1, pitch: 1 } as UtteranceSettings);
        // 播放配置
       // const curRsourceInfo = inject<ResourceInfo>('curResource');
       // const curResourceCourse = inject<ResourceCourse>('curResourceCourse');
       
       const curShareType = inject<ShareType>('curShareInfo');

        const state = reactive({
            playMode: 0, // 播放模式
            playProgress: '0', //播放进度
            curCourseId: 'default',
            hightlightText: '',
            playing: false,
            totalLength: 0,
            curType:'title',//是标题还是内容
            speechLength: 0
        });

        // 处理播放模式
        const playModeTip = ref('d-none');
        const playModeChange = () => {
            let tPlayMode = state.playMode + 1;
            state.playMode = tPlayMode % PlayModes.length;
            playModeTip.value = 'd-block';
            setTimeout(() => {
                playModeTip.value = 'd-none';
            }, 800);
        };

        onBeforeMount(() => {
            // 初始绑定
            if (curShareType?.curResource) {
                curInfo.value = curShareType.curResource;
                state.totalLength = curInfo.value['title'].length + curInfo.value['content'].length;
                let canFindCurId = curCourse.value.find((item) => item['id'] == curInfo.value['id']);
                if (!canFindCurId) {
                    curCourse.value.push(curInfo.value);
                }
            }
        });
        // 监听当前变化,更新当前科目
        watch(() => state.curCourseId,
            (newVal, oldVal) => {}
        );
        // 当前资料更新
         watch(curInfo, (newValue, oldValue) => {
            // 应该先判断是否在
            let canFindInCourse=curCourse.value.find(item=>item.id==newValue.id);
            if(!canFindInCourse){
                curCourse.value.push(newValue);
            }             
            const { progress, speechState } = useTextToSpeech(newValue, context, curUtteranceSettings);
            //const sSpeechState=ref(speechState);
            /**
             * 播放状态
             */
            watch(speechState, (newVal, oldVal) => {
                switch (newVal) {
                    case 'titleStart':
                        state.playing = true;
                        state.curType='title';
                        break;
                    case 'contentStart':
                        state.curType='content';
                        break
                    case 'contentEnd':
                        state.curType='finish';
                        break;
                    default:
                }
            });
            /**
             * 更新进度
             */
            watch(progress, (newValue, oldValue) => {
                state.totalLength = newValue.totalLength;
                state.speechLength = newValue.speechLength;
                state.playProgress = newValue.realProgress + '%';
                getDetailHTML(newValue.highlightText);
            });
        });
        const getDetailHTML=(highText)=>{   
       
            let tHTML=state.curType=='title'?`<h4 class="text-center">${highText}</h4>`:`<h4 class="${'read-title-'+state.curType}">${curInfo.value.title}</h4>`;
            tHTML+=state.curType=='content'?`<p>${highText}</p>`:`<p class=${'read-content-'+state.curType}>${curInfo.value.content}</p>`;
          
            state.hightlightText=tHTML;
        }
        // 播放资料变更
        watch(
            () => curShareType?.curResource,
            (newValue, oldValue) => {
                if (newValue) {                   
                    curInfo.value = newValue;
                }

                //当前资料
            }
        );
        // 播放科目变更
         watch(()=>curShareType?.curResourceCourse,(newValue, oldValue) => {
            // 触发变更
            if(newValue)
            curCourse.value=newValue.resourceList.filter(item=>item.title&&item.content);
         });
        const proficiencyChanged = (e) => {
            console.log(e);
        };
        //显示播放列表
        const showPlayList = ref(false);
        // 暂停、播放
        const playStateChange = () => {
            if (state.playing) {
                //当前播放点击暂停
                setPause();
            } else {
                //当前暂停，点击播放
                setContinue();
            }
        };
        // 设置暂停
        const setPause = () => {
            //当前播放点击暂停
            state.playing = false;
            window.speechSynthesis.pause();
        };
        // 继续播放
        const setContinue = () => {
            state.playing = true;
            window.speechSynthesis.resume();
        };
        
        return () => {
            return (<div class="g-btmbar">
                {curInfo.value?
                <div class={"mem-playbar"+(curInfo.value?' show':'')}>
                    <div class="hand" title="展开播放条"></div>
                    <div class="wrap" id="g_player">
                        <div class="btns">
                            <a href="javascript:;" class="prv" title="上一首(ctrl+←)">
                                上一首
                            </a>
                            <a
                                href="javascript:;"
                                class={'ply j-flag ' + (state.playing ? 'pas' : 'start')}
                                title="播放/暂停(p)"
                                onClick={(ev: MouseEvent) => playStateChange()}>
                                播放/暂停
                            </a>
                            <a href="javascript:;" class="nxt" title="下一首(ctrl+→)">
                                下一首
                            </a>
                        </div>
                        <div class="head j-flag">
                            <img src="assets/memory-voice/default-cover.png" />
                            <a href="" class="mask"></a>
                        </div>
                        <div class="play">
                            <div class="j-flag words">
                                <a href="javascript:;" class="f-thide name fc1 f-fl" title={curInfo.value.title}>
                                    {curInfo.value.title}
                                </a>
                                <span class="by f-thide f-fl">
                                    <span title="Holy Grail">
                                        <a class="" href="/artist?id=12271301">
                                            {curInfo.value?.creator}
                                        </a>
                                    </span>
                                </span>
                                <a href="#" class="src" title="来自歌单"></a>
                            </div>
                            <div class="mem-pbar" data-action="noop">
                                <div class="barbg j-flag">
                                    <div class="rdy" style="width: 0px;"></div>
                                    <div class="cur" style={{ width: state.playProgress }}>
                                        <span class="btn f-tdn f-alpha" id="auto-id-QEV5TBVekgtqVdii">
                                            <i></i>
                                        </span>
                                    </div>
                                </div>
                                <span class="j-flag time">
                                    <em>{state.speechLength}</em> / {state.totalLength}
                                </span>
                            </div>
                        </div>
                        <div class="oper f-fl">
                            <a href="javascript:;" class="icn icn-pip" title="画中画歌词">
                                画中画歌词
                            </a>
                            <a href="javascript:;" class="icn icn-add j-flag" title="收藏">
                                收藏
                            </a>
                            <a href="javascript:;" class="icn icn-share" title="分享">
                                分享
                            </a>
                        </div>
                        <div class="ctrl f-fl f-pr j-flag">
                            <div class="mem-vol" style="visibility:hidden;">
                                <div class="barbg"></div>
                                <div class="vbg j-t">
                                    <div class="curr j-t" style="height: 74.4px;"></div>
                                    <span class="btn f-alpha j-t" style="top: 16.2px;"></span>
                                </div>
                            </div>
                            <a href="javascript:;" class="icn icn-vol"></a>
                            <a
                                href="javascript:;"
                                onClick={(ev: MouseEvent) => playModeChange()}
                                class={'icn icn-' + PlayModes[state.playMode]['type']}
                                title={PlayModes[state.playMode]['text']}></a>
                            <span class="add f-pr">
                                <a
                                    href="javascript:;"
                                    data-action="panel"
                                    class="icn icn-list s-fc3"
                                    onClick={(ev: MouseEvent) => (showPlayList.value = !showPlayList.value)}>
                                    2
                                </a>
                            </span>
                            <div class={'tip tip-1 ' + playModeTip.value}>{PlayModes[state.playMode]['text']}</div>
                        </div>
                    </div>
                    <div class={'list flex-column ' + (showPlayList.value ? 'show' : '')}>
                        <div class="listhd">
                            <div class="listhdc">
                                <div class="d-flex">
                                    <div class="col-6 d-flex align-items-center justify-content-between">
                                        <h4>
                                            资料列表(<span class="j-flag">{curCourse.value.length}</span>)
                                        </h4>
                                        <a href="javascript:;" class="addall">
                                            <span class="ico ico-add">
                                                <i class="f-icon f-icon-folder-add"></i>
                                            </span>
                                            收藏资料
                                        </a>
                                    </div>
                                    <div class="col-6 d-flex align-items-center justify-content-between">
                                        <a href="javascript:;" class="clear">
                                            <span class="ico icn-del">
                                                <i class="f-icon f-icon-remove"></i>
                                            </span>
                                            清空列表
                                        </a>
                                        <span class="close" onClick={(ev: MouseEvent) => (showPlayList.value = false)}>
                                            <i class="f-icon f-icon-close"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="listbd f-utils-fill-flex-column">
                            {/* <img class="imgbg j-flag" src="" style="top: -360px;" /> */}
                            {/* <div class="msk"></div> */}
                            <f-splitter class="f-page-content">
                                <f-splitter-pane class="f-col-w6   f-page-content-nav" position="left" style="min-width: 230px">
                                    <div class="f-struct-wrapper f-utils-fill-flex-column" style="background:rgba(255,255,255,0.20)">
                                        <div class="listbdc j-flag">
                                            <ul class="f-cb">
                                                {curCourse.value.map((item, index) => (
                                                    <li id={item.id} class="pb-1">
                                                        <div class="d-flex align-items-center mb-2">
                                                            <div class="col col-1 p-0 text-center">{item.id==curInfo.value.id?<span class="f-icon f-icon-play-sm" style="color: #13C6C6;"></span>:''}</div>
                                                            <div class="col flex-fill text-truncate" style="font-size:14px;">{item.title}</div>
                                                            <div class="col col-3">
                                                                <span title="Holy Grail">
                                                                    <a class="" href="">
                                                                        {item?.creator}
                                                                    </a>
                                                                </span>
                                                            </div>
                                                            <div class="col col-2 text-left flex-shrink-0">
                                                                {item.title.length + item.content.length}
                                                            </div>                                                                
                                                            <div class="text-center flex-shrink-0">
                                                                <a href="" class="ico ico-src" title="来源">
                                                                    来源
                                                                </a>
                                                            </div>
                                                        </div>
                                                        <div class="d-flex justify-content-end">
                                                            <div class="col col-3">
                                                                <div class="icns">
                                                                    <span class="ico" title="删除">
                                                                        <i class=" f-icon f-icon-delete"></i>
                                                                    </span>
                                                                    <span class="ico" title="下载">
                                                                        <i class=" f-icon f-icon-download"></i>
                                                                    </span>
                                                                    <span class="ico" title="收藏">
                                                                        <i class=" f-icon f-icon-favorite"></i>
                                                                    </span>
                                                                </div>
                                                            </div>
                                                            <f-tags class="play-special"
                                                                data={ProficiencyLevel}
                                                                onChange={(ev: MouseEvent) => proficiencyChanged(ev)}
                                                                selectable={true}></f-tags>
                                                        </div>
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    </div>
                                </f-splitter-pane>
                                <f-splitter-pane class="f-page-content-main" position="center">
                                    <div class="listlyric j-flag flex-fill" innerHTML={state.hightlightText}></div>
                                </f-splitter-pane>
                            </f-splitter>
                        </div>
                    </div>
                </div>:''}
            </div>              
            );
        };
    }
});
